<template>
  <CommonPage>
    <template #action>
      <n-space>
        <NButton type="primary" @click="handleAdd()">
          <i class="i-material-symbols:add mr-4 text-18" />
          新增字典数据
        </NButton>
        <NButton
          :disabled="selectedIds.length === 0"
          mr-5
          type="error"
          @click="handleDelete(selectedIds)"
        >
          <i class="i-material-symbols:add mr-4 text-18" />
          批量删除
        </NButton>
      </n-space>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1200"
      :columns="columns"
      :get-data="api.readDictData"
      @on-checked="onChecked"
    >
      <MeQueryItem label="字典名称" :label-width="70">
        <n-input
          v-model:value="queryItems.name"
          type="text"
          placeholder="请输入字典名称"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="字典编码" :label-width="70">
        <n-input
          v-model:value="queryItems.code"
          type="text"
          placeholder="请输入字典编码"
          clearable
        />
      </MeQueryItem>

      <MeQueryItem label="状态" :label-width="50">
        <n-select v-model:value="queryItems.status" clearable :options="DATA_STATUS" />
      </MeQueryItem>
    </MeCrud>

    <MeModal ref="modalRef" width="520px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="110"
        :model="modalForm"
        :disabled="modalAction === 'view'"
      >
        <n-form-item
          label="字典数据名称"
          path="label"
          :rule="{
            required: true,
            message: '请输入字典数据名称',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.label" placeholder="请输入字典数据名称" />
        </n-form-item>
        <n-form-item
          label="字典数据值"
          path="value"
          :rule="{
            required: true,
            message: '请输入字典数据值',
            trigger: ['input', 'blur'],
          }"
        >
          <n-input v-model:value="modalForm.value" placeholder="请输入请输入字典数据值" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-radio-group v-model:value="modalForm.status" size="small" name="status">
            <n-radio-button
              v-for="item in DATA_STATUS"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </n-radio-group>
        </n-form-item>

        <n-form-item
          label="备注"
          path="remark"
        >
          <n-input v-model:value="modalForm.remark" placeholder="请输入备注" />
        </n-form-item>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { CommonPage, MeCrud, MeModal, MeQueryItem } from '@/components'
import { useCrud } from '@/composables'
import { NButton, NSwitch } from 'naive-ui'
import { useTemplateRef } from 'vue'
import api from './api'

defineOptions({ name: 'DictData' })

const route = useRoute()

const $table = useTemplateRef('$table')
const queryItems = ref({
  type_id: route.query.id,
})

// 状态字典-> 数据状态
const { DATA_STATUS } = $dict('DATA_STATUS')

onMounted(() => {
  $table.value?.handleSearch()
})

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleEdit,
  handleDelete,
} = useCrud({
  name: '字典数据',
  initForm: { status: '0', sort: 0, type_id: +route.query.id },
  doCreate: api.createDictData,
  doDelete: api.deleteDictData,
  doUpdate: api.updateDictData,
  refresh: () => $table.value?.handleSearch(),
})

const columns = [
  { type: 'selection' },
  { title: 'ID', key: 'id', width: 80 },
  { title: '字典名称', key: 'label', width: 250 },
  { title: '字典值', key: 'value', width: 250 },
  {
    title: '状态',
    key: 'status',
    render: row =>
      h(
        NSwitch,
        {
          value: row.status,
          loading: !!row.statusLoading,
          checkedValue: '0',
          unCheckedValue: '1',
          onUpdateValue: () => handleEnable(row),
        },
        {
          checked: () => '启用',
          unchecked: () => '停用',
        },
      ),
  },
  {
    title: '备注',
    key: 'remark',
  },
  {
    title: '创建时间',
    key: 'created_at',
    width: 180,
  },
  {
    title: '操作',
    key: 'actions',
    width: 320,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return [
        h(
          NButton,
          {
            size: 'small',
            text: true,
            type: 'primary',
            onClick: () => handleEdit(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:tool text-14' }),
          },
        ),
        row.is_system !== 1 && h(
          NButton,
          {
            text: true,
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete([row.id], row.name),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },
]

const selectedIds = ref([])
function onChecked(ids) {
  selectedIds.value = ids
}

async function handleEnable(row) {
  row.statusLoading = true
  try {
    const { message } = await api.updateDictDataStatus({ id: row.id, status: row.status === '0' ? '1' : '0' })
    row.status = row.status === '0' ? '1' : '0'
    $message.success(message)
  }
  finally {
    row.statusLoading = false
  }
}
</script>
